let sotk = null;
let socketOpen = false;

const ws_connect = (data) => {
	console.log(data)
	sotk = wx.connectSocket({
		url: 'ws://192.168.6.6:2880/wchat', //自己的ws地址
		header: {
			'content-type': 'application/json',
			'token': data
		},
		success: () => {
			// this.socketIsOpen = false;
			console.log("ws连接中：")
		},
		fail: (e) => {
			console.log("ws连接fail：" + e.errMsg, 1)
		}
	})
	console.log(sotk)
	sotk.onOpen(res => {
		socketOpen = true;
		console.log('监听 WebSocket 连接打开事件。', res);
	})
	sotk.onClose(onClose => {
		socketOpen = false;
		console.log('监听 WebSocket 连接关闭事件。', onClose)
	})
	sotk.onError(onError => {
		socketOpen = true;
		console.log('监听 WebSocket 错误。错误信息', onError)
	})
}

//发送信息
const sendMsg = (msg, success) => {
	console.log(msg)
	if (socketOpen) {
		sotk.send({
			data: JSON.stringify(msg)
		}, function(res) {
			success(res)
		})
	}
}

//接收信息
const onMessage = (reMsg) => {
	if (socketOpen) {
		sotk.onMessage(onMessage => {
			reMsg(JSON.parse(onMessage.data));
		})
	}
}

//关闭
const closeWebsocket = () => {
	if (socketOpen) {
		sotk.onClose(onClose => {
			socketOpen = false;
			console.log('监听 WebSocket 连接关闭事件。', onClose)
		})
	}
}

module.exports = {
	ws_connect,
	sendMsg,
	onMessage,
	closeWebsocket
}